import re
import time
from typing import Any, Dict, Union

def benchmark_regex(
    regex: str,
    test_value: Any,
    times: int = 10000
) -> Dict[str, Union[str, float, bool, int]]:
    """
    统计正则表达式：
      - 编译耗时（re.compile）
      - 匹配总耗时
      - 平均每次匹配耗时
    """
    # 🔹 1. 统计 re.compile 耗时
    compile_start = time.perf_counter()
    try:
        pattern = re.compile(regex)
    except re.error as e:
        return {"error": f"Invalid regex: {e}"}
    compile_time = time.perf_counter() - compile_start
    compile_time_ns = compile_time * 1_000_000_000  # 转为纳秒

    # 如果不是字符串，无法匹配
    if not isinstance(test_value, str):
        match_result = False
        match_elapsed = 0.0
        avg_match_time_ns = 0.0
    else:
        # 🔹 2. 统计多次匹配耗时
        match_start = time.perf_counter()
        match_count = 0

        for _ in range(times):
            if pattern.search(test_value):
                match_count += 1

        match_elapsed = time.perf_counter() - match_start
        match_result = match_count > 0
        avg_match_time_ns = (match_elapsed / times) * 1_000_000_000

    return {
        "regex": regex,
        "test_value": test_value,
        "matches": match_result,
        "compile_time_ms": round(compile_time * 1000, 4),       # 毫秒
        "compile_time_ns": round(compile_time_ns, 2),           # 纳秒
        "total_match_time_sec": round(match_elapsed, 6),
        "avg_time_per_match_ms": round((match_elapsed / times) * 1000, 4),
        "avg_time_per_match_ns": round(avg_match_time_ns, 2),
        "runs": times,
    }

result = benchmark_regex(
    regex=r"^1[3-9]\d{9}$",
    test_value="13812345678",
    times=50000
)

# 打印结果
import json
print(json.dumps(result, indent=2, ensure_ascii=False))